import { defineStore } from 'pinia';
import { getUserInfo, updateUserInfo } from '@/api/user/user';

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: {
      id: null,
      email: '',
      username: '',
      nickname: '',
      sex: null,
      company: '',
      introduce: '',
      avatar: '',
      role: null,
      createdAt: '',
      updatedAt: ''
    }
  }),
  actions: {
    async fetchUserInfo() {
      try {
        const res = await getUserInfo();
        if (res.data && res.data.user) {
          this.userInfo = res.data.user;
        }
        return res;
      } catch (error) {
        console.error('获取用户信息失败:', error);
        throw error;
      }
    },
    async updateUserInfo(data) {
      try {
        const res = await updateUserInfo(data);
        if (res.data && res.data.user) {
          this.userInfo = { ...this.userInfo, ...res.data.user };
        }
        return res;
      } catch (error) {
        console.error('更新用户信息失败:', error);
        throw error;
      }
    }
  }
});